package cn.edu.xmist.supermarket.dw.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

  @Autowired private HttpSession httpSession;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String uri = request.getRequestURI();
    /**
     * HandlerMethod=>Controller中标注@RequestMapping的方法
     *
     * <p>需要配置静态资源不拦截时，添加这块逻辑 => 前后端分离项目
     */
    if (!(handler instanceof HandlerMethod)) {
      return true;
    }

    if (httpSession.getAttribute("user") == null) {
      // 未登录跳转到登录界面
      response.sendRedirect("/user/loginHtml");
      return false;
    }
    return true;
  }
}
